<template>
  <div class="sales-orders-container">
    <!-- 业务模式视图 -->
    <div v-show="viewMode === 'business'">
      <SalesOrderStats :stats="stats" />
      
      <el-card class="filter-card" shadow="never">
        <SalesOrderFilter 
          :query-params="queryParams"
          @search="handleSearch"
          @reset="handleReset"
          @export="handleExport"
          @import="handleImport"
          @sync="handleSync"
        />
      </el-card>
      
      <el-card class="table-card" shadow="never">
        <template #header>
          <div class="table-header">
            <div class="header-left">
              <el-button type="primary" :icon="Plus" @click="showOrderDialog">
                新增订单
              </el-button>
              <el-button :icon="Delete" :disabled="selectedOrders.length === 0" @click="handleBatchDelete">
                批量删除
              </el-button>
              <el-button :icon="Upload" :disabled="selectedOrders.length === 0" @click="handleBatchInvoice">
                批量开票
              </el-button>
              <el-button :icon="Van" :disabled="selectedOrders.length === 0" @click="handleBatchDelivery">
                批量发货
              </el-button>
            </div>
            <div class="header-right">
              <el-button-group>
                <el-button 
                  :type="viewMode === 'business' ? 'primary' : 'default'" 
                  @click="viewMode = 'business'"
                >
                  业务模式
                </el-button>
                <el-button 
                  :type="viewMode === 'data' ? 'primary' : 'default'" 
                  @click="viewMode = 'data'"
                >
                  数据模式
                </el-button>
              </el-button-group>
            </div>
          </div>
        </template>
        
        <SalesOrderTable 
          :table-data="salesOrders || []"
          :loading="loading"
          :pagination="pagination"
          @selection-change="handleSelectionChange"
          @view-detail="viewOrderDetail"
          @edit="editOrder"
          @delivery="handleDelivery"
          @page-change="handlePageChange"
          @size-change="handleSizeChange"
          @sort-change="handleSortChange"
        />
      </el-card>
      
      <SalesOrderSmartAlerts :orders="salesOrders || []" />
    </div>
    
    <!-- 数据管理模式视图 -->
    <div v-show="viewMode === 'data'">
      <OrderPageHeader 
        :stats="statsData"
        :syncing="syncing"
        :selected-orders="selectedOrders"
        @sync-orders="handleSync"
        @import-orders="showImportWizard = true"
        @export-orders="handleExport"
        @batch-operations="handleBatchOperations"
      />
      
      <OrderStatsOverview :stats="statsData" />
      
      <el-card class="filter-card" shadow="never">
        <OrderFilterForm 
          :query-params="queryParams"
          @search="handleSearch"
          @reset="handleReset"
        />
      </el-card>
      
      <el-card class="table-card" shadow="never">
        <template #header>
          <div class="table-header">
            <div class="header-left">
              <el-button type="primary" :icon="Plus" @click="showOrderDialog">
                新增订单
              </el-button>
              <el-button :icon="Delete" :disabled="selectedOrders.length === 0" @click="handleBatchDelete">
                批量删除
              </el-button>
              <el-button :icon="Upload" :disabled="selectedOrders.length === 0" @click="handleBatchInvoice">
                批量开票
              </el-button>
              <el-button :icon="Van" :disabled="selectedOrders.length === 0" @click="handleBatchDelivery">
                批量发货
              </el-button>
            </div>
            <div class="header-right">
              <el-button-group>
                <el-button 
                  :type="viewMode === 'business' ? 'primary' : 'default'" 
                  @click="viewMode = 'business'"
                >
                  业务模式
                </el-button>
                <el-button 
                  :type="viewMode === 'data' ? 'primary' : 'default'" 
                  @click="viewMode = 'data'"
                >
                  数据模式
                </el-button>
              </el-button-group>
            </div>
          </div>
        </template>
        
        <OrderTable 
          :table-data="salesOrders || []"
          :loading="loading"
          :pagination="pagination"
          @selection-change="handleSelectionChange"
          @view-detail="showDataOrderDetail"
          @edit="editDataOrder"
          @delivery="handleDelivery"
          @page-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </el-card>
    </div>
    
    <!-- 业务模式对话框 -->
    <SalesOrderOperationDialog
      v-model="showDialog"
      :editing-order="editingOrder"
      @success="saveOrder"
      @close="handleDialogClose"
    />
    
    <SalesOrderDetailDialog
      v-model="detailDialogVisible"
      :order="detailOrder"
      @close="handleDetailDialogClose"
    />
    
    <SalesOrderImportWizard
      v-model="importWizardVisible"
      @success="handleImportSuccess"
      @cancel="handleImportCancel"
    />
    
    <!-- 数据管理模式组件 -->
    <InvoiceDialog 
      v-model="showInvoiceDialog"
      :order="currentOrderForInvoice"
      @success="handleInvoiceSuccess"
      @close="handleInvoiceClose"
    />
    
    <OrderImportWizard
      v-model="showImportWizard"
      @success="handleImportSuccess"
      @cancel="handleImportCancel"
    />
    
    <OrderDetailDrawer
      v-model="showOrderDetailDrawer"
      :order-id="Number(currentOrderId)"
      @refresh="handleOrderRefresh"
    />
    
    <OrderEditDrawer
      v-model="showOrderEditDrawer"
      :order-id="currentOrderId"
      @success="handleOrderUpdated"
    />
    
    <!-- 发货对话框 -->
    <DeliveryDialog
      v-model="showDeliveryDialog"
      :order-data="currentOrderForDelivery"
      @success="handleDeliverySuccess"
      @cancel="handleDeliveryCancel"
    />
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Upload, Van } from '@element-plus/icons-vue'
import * as salesAPI from '@/api/sales'
import type { SalesOrder } from '@/types/order'

// 业务模式组件
import SalesOrderStats from './components/SalesOrderStats.vue'
import SalesOrderFilter from './components/SalesOrderFilter.vue'
import SalesOrderTable from './components/SalesOrderTable.vue'
import SalesOrderSmartAlerts from './components/SalesOrderSmartAlerts.vue'
import SalesOrderOperationDialog from './components/SalesOrderOperationDialog.vue'
import SalesOrderDetailDialog from './components/SalesOrderDetailDialog.vue'
import SalesOrderImportWizard from './components/SalesOrderImportWizard.vue'

// 数据管理模式组件
import OrderPageHeader from './data-components/OrderPageHeader.vue'
import OrderStatsOverview from './data-components/OrderStatsOverview.vue'
import OrderFilterForm from './data-components/OrderFilterForm.vue'
import OrderTable from './data-components/OrderTable.vue'
import InvoiceDialog from './data-components/InvoiceDialog.vue'
import OrderImportWizard from './data-components/OrderImportWizard.vue'
import OrderDetailDrawer from './data-components/OrderDetailDrawer.vue'
import OrderEditDrawer from './data-components/OrderEditDrawer.vue'
import DeliveryDialog from '@/components/delivery/DeliveryDialog.vue'

// 响应式数据
const viewMode = ref('business')
const loading = ref(false)
const syncing = ref(false)
const showDialog = ref(false)
const detailDialogVisible = ref(false)
const importWizardVisible = ref(false)
const showInvoiceDialog = ref(false)
const showImportWizard = ref(false)
const showOrderDetailDrawer = ref(false)
const showOrderEditDrawer = ref(false)
const showDeliveryDialog = ref(false)

// 订单数据
const salesOrders = ref<SalesOrder[]>([])
const selectedOrders = ref<SalesOrder[]>([])
const editingOrder = ref<SalesOrder | null>(null)
const detailOrder = ref<SalesOrder | null>(null)
const currentOrderId = ref('')
const currentOrderForDelivery = ref<SalesOrder | null>(null)
const currentOrderForInvoice = ref<SalesOrder | null>(null)

// 统计数据
const stats = ref({
  totalOrders: 0,
  pendingOrders: 0,
  completedOrders: 0,
  problemOrders: 0,
  monthlyAmount: 0,
  avgOrderAmount: 0,
  completionRate: 0,
  uninvoicedOrders: 0,
  amountTrend: 0,
  avgTrend: 0,
  completionTrend: 0,
  invoiceTrend: 0
})

const statsData = ref({
  totalOrders: 0,
  pendingOrders: 0,
  completedOrders: 0,
  problemOrders: 0,
  totalAmount: 0
})

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 智能提醒
const smartAlerts = ref<any[]>([])

// 查询参数
const queryParams = reactive({
  orderNumber: '',
  customerId: null,
  orderStatus: '',
  invoiceStatus: '',
  dateRange: [] as string[],
  minAmount: undefined,
  maxAmount: undefined,
  salesperson: '',
  page: 1,
  limit: 20
})

// 计算属性
const canBatchOperation = computed(() => selectedOrders.value.length > 0)

// 方法
const showOrderDialog = () => {
  editingOrder.value = null
  showDialog.value = true
}

const viewOrderDetail = (order: SalesOrder) => {
  detailOrder.value = order
  detailDialogVisible.value = true
}

const editOrder = (order: SalesOrder) => {
  editingOrder.value = order
  showDialog.value = true
}

const handleDialogClose = () => {
  showDialog.value = false
  editingOrder.value = null
}

const handleDetailDialogClose = () => {
  detailDialogVisible.value = false
  detailOrder.value = null
}

const handleImportSuccess = () => {
  loadSalesOrders()
  importWizardVisible.value = false
  showImportWizard.value = false
}

const handleImportCancel = () => {
  importWizardVisible.value = false
  showImportWizard.value = false
}

const saveOrder = async (orderData: any) => {
  try {
    if (editingOrder.value) {
      // 更新订单
      await salesAPI.updateSalesOrder(editingOrder.value.id, orderData)
      ElMessage.success('订单更新成功')
    } else {
      // 创建订单
      await salesAPI.createSalesOrder(orderData)
      ElMessage.success('订单创建成功')
    }
    handleDialogClose()
    loadSalesOrders()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadSalesOrders()
}

const handleReset = () => {
  Object.assign(queryParams, {
    orderNumber: '',
    customerId: null,
    orderStatus: '',
    invoiceStatus: '',
    dateRange: [],
    minAmount: undefined,
    maxAmount: undefined,
    salesperson: ''
  })
  pagination.page = 1
  loadSalesOrders()
}

const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

const handleImport = () => {
  importWizardVisible.value = true
}

const handleSync = async () => {
  syncing.value = true
  try {
    // 模拟同步过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('订单同步完成')
    loadSalesOrders()
  } catch (error) {
    ElMessage.error('同步失败')
  } finally {
    syncing.value = false
  }
}

const handleBatchDelete = async () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要删除的订单')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedOrders.value.length} 个订单吗？`, '提示', {
      type: 'warning'
    })
    
    const ids = selectedOrders.value.map((order: SalesOrder) => order.id)
    await salesAPI.deleteSalesOrder(ids[0]) // 临时使用单个删除，后续需要批量删除API
    ElMessage.success('删除成功')
    loadSalesOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchInvoice = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要开票的订单')
    return
  }
  ElMessage.info('批量开票功能开发中')
}

const handleBatchDelivery = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要发货的订单')
    return
  }
  ElMessage.info('批量发货功能开发中')
}

const handleBatchOperations = (orders: SalesOrder[]) => {
  ElMessage.info(`批量操作 ${orders.length} 个订单`)
}

const handleSelectionChange = (selection: SalesOrder[]) => {
  selectedOrders.value = selection
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadSalesOrders()
}

const handleSizeChange = (limit: number) => {
  pagination.limit = limit
  pagination.page = 1
  loadSalesOrders()
}

const handleSortChange = (sort: any) => {
  console.log('排序:', sort)
}

const showDataOrderDetail = (order: SalesOrder) => {
  currentOrderId.value = order.id
  showOrderDetailDrawer.value = true
}

const editDataOrder = (order: SalesOrder) => {
  currentOrderId.value = order.id
  showOrderEditDrawer.value = true
}

const handleDelivery = (order: SalesOrder) => {
  currentOrderForDelivery.value = order
  showDeliveryDialog.value = true
}

const handleDeliverySuccess = () => {
  showDeliveryDialog.value = false
  currentOrderForDelivery.value = null
  loadSalesOrders()
}

const handleDeliveryCancel = () => {
  showDeliveryDialog.value = false
  currentOrderForDelivery.value = null
}

const handleInvoiceSuccess = () => {
  showInvoiceDialog.value = false
  currentOrderForInvoice.value = null
  loadSalesOrders()
}

const handleInvoiceClose = () => {
  showInvoiceDialog.value = false
  currentOrderForInvoice.value = null
}

const handleOrderRefresh = () => {
  loadSalesOrders()
}

const handleOrderUpdated = () => {
  showOrderEditDrawer.value = false
  currentOrderId.value = ''
  loadSalesOrders()
}

const loadSalesOrders = async () => {
  loading.value = true
  try {
    const response = await salesAPI.getSalesOrders({
      ...queryParams,
      page: pagination.page,
      limit: pagination.limit
    } as any)
    
    // 确保数据是数组格式
    salesOrders.value = Array.isArray(response.list) ? response.list : []
    pagination.total = response.pagination?.total || 0
    
    // 加载统计数据
    loadStats()
  } catch (error) {
    ElMessage.error('加载订单列表失败')
    // 发生错误时确保salesOrders是空数组
    salesOrders.value = []
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await salesAPI.getSalesOrderStats()
    stats.value = response
    statsData.value = {
      totalOrders: response.totalOrders,
      pendingOrders: response.pendingOrders,
      completedOrders: response.completedOrders,
      problemOrders: response.problemOrders || 0,
      totalAmount: 0 // 需要从API获取
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 发生错误时设置默认值
    stats.value = {
      totalOrders: 0,
      pendingOrders: 0,
      completedOrders: 0,
      problemOrders: 0,
      monthlyAmount: 0,
      avgOrderAmount: 0,
      completionRate: 0,
      uninvoicedOrders: 0,
      amountTrend: 0,
      avgTrend: 0,
      completionTrend: 0,
      invoiceTrend: 0
    }
    statsData.value = {
      totalOrders: 0,
      pendingOrders: 0,
      completedOrders: 0,
      problemOrders: 0,
      totalAmount: 0
    }
  }
}

// 生命周期
onMounted(() => {
  loadSalesOrders()
})
</script>

<style scoped lang="scss">
.sales-orders-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  gap: 12px;
}

.header-right {
  display: flex;
  align-items: center;
}

@media (max-width: 768px) {
  .sales-orders-container {
    padding: 12px;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .header-left {
    flex-wrap: wrap;
  }
}
</style>